package pyip.lib.javalearn.thread.happensbefore;

import java.util.Date;

/**
 * @author yepeng
 * @date 2015年5月21日
 */
public class SingleInstanceSynchronizedDemo {

    private static class TestObject {
        private static TestObject instance;
        private Date date;

        public static TestObject getInstance() {
            if (instance == null) {
                synchronized (TestObject.class) {
                    instance = new TestObject();
                    instance.date = new Date();
                }
            }
            return instance;
        }

        public synchronized static void destroy() {
            instance = null;
        }

        public Date getDate() {
            return date;
        }
    }

    private static Runnable r = new Runnable() {
        private Integer counter = 0;

        @Override
        public void run() {
            TestObject obj = TestObject.getInstance();
            synchronized (counter) {
                counter++;
                try {
                    System.out.println(counter + " " + obj.getDate().getTime());
                } catch (Exception e) {
                    System.err.println(counter + " obj.getDate:" + obj.getDate());
                    e.printStackTrace();
                }
            }
        }
    };

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(r).start();
            new Thread(r).start();
            TestObject.destroy();
        }
    }

}
